<template>
  <div class="permission">
    <el-card class="top">
      <div style="text-align: right">
        <el-button type="primary" @click="addEvent">添加权限</el-button>
      </div>
    </el-card>
    <el-table :data="list" border row-key="id">
      <el-table-column label="名称" prop="name" />
      <el-table-column label="标识" prop="code" />
      <el-table-column label="描述" prop="description" />
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            v-if="row.type === 1"
            type="text"
            @click="addEvent2(row.id)"
          >添加</el-button>
          <el-button type="text" @click="editEvent(row)">编辑</el-button>
          <el-button type="text" @click="delEvent(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Add ref="add" @getData="getData" />
  </div>
</template>

<script>
import { sysPermission, sysPermissionDel } from '@/api/permission'
import Add from './coponents/add.vue'
export default {
  components: {
    Add
  },
  data() {
    return {
      list: [{}]
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysPermission()
      this.list = this.changeData(res.data, '0')
    },
    // 树形数据转换
    changeData(arr, pid) {
      return arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    },
    addEvent() {
      this.$refs.add.isShow = true
      this.$refs.add.model = 'add'
    },
    addEvent2(id) {
      this.$refs.add.isShow = true
      this.$refs.add.model = 'add'
      this.$refs.add.form.type = 2
      this.$refs.add.form.pid = id
    },
    editEvent(row) {
      this.$refs.add.isShow = true
      this.$refs.add.model = 'edit'
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
    },
    delEvent(id) {
      this.$confirm('您确定删除该项吗?')
        .then(async() => {
          await sysPermissionDel(id)
          this.$message.success('删除成功')
          this.getData()
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
  .top {
    margin-bottom: 15px;
  }
}
</style>
